// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
mod app_handle_manager; // 声明模块
mod tray;

use app_handle_manager::AppHandleManager;
use tauri::{Emitter, Manager, Window};
// 引入结构体
use tauri_plugin_dialog::DialogExt;
use tauri_plugin_updater::UpdaterExt;
use tray::try_register_tray_icon;
#[cfg(target_os = "macos")]
use cocoa::appkit::{NSColor, NSWindow};
#[cfg(target_os = "macos")]
use cocoa::base::{id, nil};

#[tauri::command]
fn update_tray_title(title: &str) {
    if let Some(tray) = AppHandleManager::global().get_tray() {
        let title = title.to_string();
        tauri::async_runtime::spawn(async move {
            if let Err(e) = tray.set_title(Some(&title)) {
                eprintln!("设置托盘标题失败: {:?}", e);
            }
        });
    }
}

#[tauri::command]
fn update_app(token: &str, window: Window, force: bool) {
    println!("更新测试开始啦......");
    println!("token是多少：{}", token);
    let token_owned = token.to_string();
    tauri::async_runtime::spawn(async move {
        update(&token_owned, force).await.unwrap();
        if !force {
            if !window.is_enabled().unwrap_or(false) {
                window.set_enabled(true);
                window.set_focus();
            }
        }
    });
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    let app = tauri::Builder::default()
        .plugin(tauri_plugin_updater::Builder::new().build())
        .setup(|app| {
            // 托盘
            AppHandleManager::global().init(app.handle().clone());
            try_register_tray_icon(app.handle())?;

            // let window = app.build().unwrap();

            #[cfg(target_os = "macos")]
            unsafe {
                if let Some(window) = app.get_webview_window("main") {

                    let ns_window = window.ns_window().unwrap() as id;
                    let bg_color = NSColor::colorWithRed_green_blue_alpha_(
                        nil,
                        245.0 / 255.0,
                        246.0 / 255.0,
                        247.0 / 255.0,
                        1.0,
                    );
                    ns_window.setBackgroundColor_(bg_color);
                }
            }

            Ok(())
        })
        .plugin(tauri_plugin_shell::init())
        .plugin(tauri_plugin_dialog::init())
        .plugin(tauri_plugin_fs::init())
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![update_tray_title, update_app])
        .build(tauri::generate_context!())
        .expect("error while running tauri application");

    app.run(|app_handle, e| match e {
        #[cfg(target_os = "macos")]
        tauri::RunEvent::Reopen {
            has_visible_windows,
            ..
        } => {
            if !has_visible_windows {
                if let Some(window) = AppHandleManager::global()
                    .get_handle()
                    .get_webview_window("main")
                {
                    window.show();
                }
            }
        }
        _ => {}
    });
}

async fn update(_token: &str, force: bool) -> tauri_plugin_updater::Result<()> {
    let app = AppHandleManager::global().get_handle();
    // let author =  format!(
    //     "Bearer {token}",
    //     token = _token.trim_matches('"').to_string()
    // );
    let target = "windows";
    #[cfg(target_os = "macos")]
    let target = "macos";

    println!("开始检查更新，target: {}", target);
    println!("token是多少：{}", _token);
    // 移除Authorization头部要求，允许未登录用户也能自动更新
    if let Some(update) = app.updater_builder()
        .target(target)
        // .header("Authorization", author)? // 移除认证要求
        .build()?.check().await? {
        if let Some(_window) = app.get_webview_window("main")  {
            if !force {
                // window.set_enabled(false);
                // 暂时禁用窗口，但不影响对话框显示
                println!("准备显示更新对话框");
            }
        }
         // 弹出确认对话框
        let body_display = update.body.as_ref().unwrap_or(&"无更新内容".to_string()).to_owned();
        let content =  format!(
            "版本: {version} \r\n 更新内容: {body}",
            version = update.version,
            body = body_display
        );
        let mut confirmed = true;
        if !force {
            println!("显示更新确认对话框");
            confirmed = app.dialog()
                .message(content)     
                .buttons(tauri_plugin_dialog::MessageDialogButtons::YesNo)
                .title("发现新版本，是否立即更新？")
                .blocking_show();
                println!("用户选择: {}", if confirmed { "确认更新" } else { "取消更新" });
        }

        // 点击确认 之后下载安装 重启
        // 根据用户选择处理
        if confirmed {
            // 现在才禁用窗口，开始下载
            if let Some(window) = app.get_webview_window("main") {
                if !force {
                    window.set_enabled(false);
                }
            }

            let mut downloaded = 0;
            println!("开始下载更新...");
            // alternatively we could also call update.download() and update.install() separately
            update
            .download_and_install(
                |chunk_length, content_length| {
                    downloaded += chunk_length;
                    // contentLength = content_length;
                    let size = content_length.unwrap_or(1);
                    let progress = downloaded as u64 * 100 / size;
                    println!("下载进度: {}%", progress);
                    app.emit("update-version-process", progress);
                },
                || {
                    println!("download finished");
                },
            )
            .await?;

            println!("update installed");
            println!("更新安装完成，准备重启应用");
            app.restart();
        } else {
            // 用户取消更新，重新启用窗口
            if let Some(window) = app.get_webview_window("main") {
                window.set_enabled(true);
                window.set_focus();
            }
        }
    } else {
        println!("当前已是最新版本");
    }

    Ok(())
}